package com.fanfan.SmartPensionSystembackend.mapper;

import com.fanfan.SmartPensionSystembackend.entity.Payment;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @Description PaymentMapper
 * @Author Guangdi Chen
 * @Date 2025-03-30
 */
@Mapper
public interface PaymentMapper {
    // 获取所有老人信息
    @Select("SELECT e.elderId, e.name, e.gender, e.birthdate, e.admissionTime, b.bedPlace, f.balance " +
            "FROM elder e " +
            "LEFT JOIN bed b ON e.bedId = b.bedId " +
            "LEFT JOIN finance f ON e.elderId = f.elderId")
    List<Payment> getAllElderInfo();

    // 根据老人ID获取老人信息
    @Select("SELECT e.elderId, e.name, e.gender, e.birthdate, e.admissionTime, b.bedPlace, f.balance " +
            "FROM elder e " +
            "LEFT JOIN bed b ON e.bedId = b.bedId " +
            "LEFT JOIN finance f ON e.elderId = f.elderId " +
            "WHERE e.elderId = #{elderId}")
    Payment getElderInfoById(String elderId);

    // 一键插入所有老人的月固定费用
    @Update({"<script>",
            "INSERT INTO finance (elderId, stayCost, foodCost, nursingCost, billNo, paymentDate)",
            "SELECT e.elderId, #{stayCost}, #{foodCost}, #{nursingCost}, ",
            "       CONCAT(e.elderId, DATE_FORMAT(NOW(), '%Y%m%d')), NOW()",
            "FROM elder e",
            "ON DUPLICATE KEY UPDATE",
            "  stayCost = VALUES(stayCost),",
            "  foodCost = VALUES(foodCost),",
            "  nursingCost = VALUES(nursingCost),",
            "  paymentDate = NOW();",

            "UPDATE finance",
            "SET balance = balance - (#{stayCost} + #{foodCost} + #{nursingCost})",
            "WHERE elderId IN (SELECT elderId FROM elder);",
            "</script>"})
    @Transactional
    int pushAllFixedCost(Map<String, Double> fixationFeeInfo);

    // 插入或更新特殊费用
    @Update({"<script>",
            "INSERT INTO finance (elderId, specialCost, remark, billNo, paymentDate, balance)",
            "SELECT #{elderId}, #{specialCost}, #{remark}, ",
            "       CONCAT(#{elderId}, DATE_FORMAT(NOW(), '%Y%m%d')), NOW(), ",
            "       IFNULL((SELECT balance FROM finance WHERE elderId = #{elderId}), 0) - #{specialCost}",
            "FROM elder e",
            "WHERE e.elderId = #{elderId}",
            "ON DUPLICATE KEY UPDATE",
            "  specialCost = VALUES(specialCost),",
            "  remark = VALUES(remark),",
            "  paymentDate = NOW(),",
            "  balance = balance - #{specialCost};",
            "</script>"})
    @Transactional
    int insertOrUpdateSpecialCost(Map<String, Object> specialCostInfo);
}